"use client";
import React, {
  useState,
  useEffect,
  useRef,
  useMemo,
  useCallback,
} from "react";
import ReactEChartsCore from "echarts-for-react/lib/core";
import * as echarts from "echarts/core";
import type EChartsReact from "echarts-for-react";
import Image from "next/image";
import "animate.css";
import {
  LineChart,
  ScatterChart,
  EffectScatterChart,
  LinesChart,
} from "echarts/charts";
import {
  GridComponent,
  TooltipComponent,
  TitleComponent,
  LegendComponent,
  GeoComponent,
  GraphicComponent,
} from "echarts/components";
import { CanvasRenderer } from "echarts/renderers";
import { useMapData } from "../../hooks/useMapData";
import worldJson from "./world.json";
import styles from "./style.module.scss";
import jin from "../../images/jin.svg";
import yin from "../../images/yin.svg";
import tong from "../../images/tong.svg";
import icon_arrow from "../Title/icon_arrow.svg";
import wIcon from "../../images/po.svg";
import data from "./data.json";

echarts.use([
  CanvasRenderer,
  LineChart,
  LinesChart,
  ScatterChart,
  GeoComponent,
  GraphicComponent,
  LegendComponent,
  TooltipComponent,
  TitleComponent,
  GridComponent,
]);

if (process.env.NEXT_PUBLIC_APP_ENV === "prod") console.log = function () {};

// 视频播放时间
let videoTime =
  typeof window !== "undefined" &&
  new URL(window.location.href).searchParams.get("videoTime");

videoTime = videoTime ? videoTime : "10000";

// 对纬度进行偏移
const processLng = (lng: number) => {
  return lng > -30 ? lng - 180 : lng + 180;
};

const formatData = (value: number) => {
  return value.toString().length > 6
    ? Math.floor(value / 1000).toLocaleString() + "K"
    : value.toLocaleString();
};

echarts.registerMap("customMap", worldJson as any);

type WearhouseData = {
  warehouseLevel: number | null;
  warehouseId: string;
  name: string;
  value: number | string;
  lang: number;
  lat: number;
  imageUrl: string;
  videoUrl: string;
  location?: number[];
};

function MapChart() {
  const { data } = useMapData();
  // console.log('data---', data);
  // 地图背景图
  const img =
    typeof window !== "undefined" && window.document.createElement("img");
  if (img) {
    img.src = "https://uat-base.oss-cn-hangzhou.aliyuncs.com/gridMini.png";
  }
  // 地图数据
  const warehouseData = useRef<any[]>(data as any[]);
  // 地图仓库信息
  const [wearhouseList, setWearhouseList] = useState<WearhouseData[]>([]);
  const mapChartRef = useRef<EChartsReact>(null);
  // 显示高亮仓库
  const [highlight, setHighlight] = useState<boolean>(false);
  // 高亮仓库信息
  const [highlightWearhouse, setHighlightHighlightWearhouse] =
    useState<number>(999);
  // 下一个高亮仓库 需要延迟后设置
  const [nextHighlightWearhouse, setNextHighlightWearhouse] =
    useState<number>(999);

  // 需要高亮的仓库
  const highlightWarehouseList = useRef<any[]>([]);
  // 在库库存标签位置

  // 国内仓索引
  const inWearhouseIndex = useRef<number>(0);
  // 当前高亮的仓库索引
  const [currentWarehouseIndex, setCurrentWarehouseIndex] = useState<number>(0);

  const renderPlayer = useCallback((item: any, index: number) => {
    return (
      <>
        {item.videoUrl ? (
          <video
            key={index}
            width="100%"
            height={425}
            autoPlay={true}
            muted
            preload="auto"
            loop={true}
            id={`video_${item.name}`}
            // src={item.videoUrl}
            style={{ objectFit: "fill", borderRadius: 10, marginTop: 12 }}
          >
            <source src={item.videoUrl} type="video/mp4" />
          </video>
        ) : (
          <Image
            src={item.imageUrl}
            style={{ marginTop: 12, borderRadius: 10 }}
            width={705}
            height={425}
            alt="pic"
          />
        )}
      </>
    );
  }, []);

  /**
   * 设置线高亮
   * @param index 仓库索引
   * @returns
   */
  const setHighlightLine = (index: number) => {
    const echartInstance = mapChartRef.current?.getEchartsInstance();
    echartInstance?.setOption(
      {
        series: [
          {
            type: "scatter",
            coordinateSystem: "geo",
            data: warehouseData.current?.map((item: any) => ({
              name: item.warehouseName,
              value: [
                processLng(Number(item.longitude)),
                Number(item.latitude),
              ],
              symbolSize: 26,
              itemStyle: {
                color: "#F0A72B",
              },
              symbol:
                "image://https://uat-base.oss-cn-hangzhou.aliyuncs.com/wIcon.png",
            })),
          },
          {
            type: "lines",
            coordinateSystem: "geo",
            polyline: true,
            lineStyle: {
              color: "#00F9B1",
              width: 3,
              type: "dashed",
              opacity: 1,
              join: "miter",
            },
            data:
              warehouseData.current
                ?.filter((i) => i.coordinatesNodes.length > 0)
                ?.map((item: any) => ({
                  coords:
                    item?.coordinatesNodes?.map((j) => [
                      processLng(Number(j.longitude)),
                      Number(j.latitude),
                    ]) || [],
                })) || [],
          },
          {
            type: "lines",
            animation: false,
            zlevel: 299,
            coordinateSystem: "geo",
            polyline: true,
            lineStyle: {
              color: "#FEA91B",
              width: 3,
              type: "dashed",
              opacity: 1,
              join: "miter",
            },

            effect: {
              show: true,
              period: 3,
              trailLength: 0,
              symbol:
                "image://https://uat-base.oss-cn-hangzhou.aliyuncs.com/glodShip270.svg",
              symbolSize: 32,
              symbolRotate: 180,
              loop: false,
            },
            data: [
              {
                coords:
                  index !== inWearhouseIndex.current
                    ? highlightWarehouseList.current[
                        index
                      ]?.coordinatesNodes.map((j) => [
                        processLng(Number(j.longitude)),
                        Number(j.latitude),
                      ]) || [[]]
                    : [[]],
              },
            ],
          },
        ],
      },
      { replaceMerge: ["series"] }
    );
  };

  // 定时器对象
  let timer: any = {};

  /**
   *
   * @param index 高亮的仓库索引
   */
  const setEffect = useCallback(
    (index: number, wearhouseLoaction: WearhouseData[]) => {
      // 更新当前仓库索引
      setCurrentWarehouseIndex(index);
      setHighlight(false);

      // if (index === inWearhouseIndex.current) {
      //   // 高亮国内仓
      //   setHighlightHighlightWearhouse(index);
      //   setHighlightLine(index);
      //   if (timer.one) clearTimeout(timer.one);
      //   timer.one = setTimeout(() => {
      //     setHighlight(true);
      //     // 播放视频后隐藏高亮仓库，高亮下一个路线
      //     if (timer.two) clearTimeout(timer.two);
      //     timer.two = setTimeout(() => {
      //       setHighlight(false);
      //       if (index < warehouseData.current.length - 1) {
      //         setEffect(index + 1, wearhouseLoaction);
      //         setNextHighlightWearhouse(index + 1);
      //       } else {
      //         setEffect(0, wearhouseLoaction);
      //         setNextHighlightWearhouse(0);
      //       }
      //     }, Number(videoTime));
      //   }, 1300);
      //   return;
      // }
      // 设置线条高亮
      setHighlightLine(index);
      // 高亮仓库tip
      setHighlightHighlightWearhouse(index);
      // 显示高亮仓库
      if (timer.fore) clearTimeout(timer.fore);
      timer.fore = setTimeout(() => {
        setHighlight(true);
        // 播放视频后隐藏高亮仓库，高亮下一个路线
        if (timer.five) clearTimeout(timer.five);
        timer.five = setTimeout(() => {
          setHighlight(false);
          if (index < highlightWarehouseList.current.length - 1) {
            setEffect(index + 1, wearhouseLoaction);
            setNextHighlightWearhouse(index + 1);
          } else {
            setEffect(0, wearhouseLoaction);
            setNextHighlightWearhouse(0);
          }
        }, Number(videoTime));
      }, 3000);
    },
    [
      setCurrentWarehouseIndex,
      setHighlightHighlightWearhouse,
      setHighlight,
      setNextHighlightWearhouse,
      videoTime,
    ]
  );

  // 手动触发 setEffect 的函数
  const manualTriggerSetEffect = useCallback(
    (direction: "up" | "down") => {
      // 清理所有现有定时器
      Object.values(timer).forEach((t: any) => {
        if (t) clearTimeout(t);
      });

      let nextIndex = currentWarehouseIndex;
      if (direction === "up") {
        nextIndex =
          currentWarehouseIndex > 0
            ? currentWarehouseIndex - 1
            : warehouseData.current.length - 1;
      } else {
        nextIndex =
          currentWarehouseIndex < warehouseData.current.length - 1
            ? currentWarehouseIndex + 1
            : 0;
      }

      setCurrentWarehouseIndex(nextIndex);
      setEffect(nextIndex, warehouseData.current);
    },
    [currentWarehouseIndex, setEffect]
  );

  // 键盘事件监听
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === "ArrowUp") {
        event.preventDefault();
        manualTriggerSetEffect("up");
      } else if (event.key === "ArrowDown") {
        event.preventDefault();
        manualTriggerSetEffect("down");
      }
    };

    // 添加键盘事件监听器
    window.addEventListener("keydown", handleKeyDown);

    // 清理函数
    return () => {
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, [manualTriggerSetEffect]);

  const option = useMemo(() => {
    const warehouseList = data.map((i) => ({
      ...i,
      coordinatesNodes: JSON.parse(i.coordinatesNodes || "[]"),
    }));
    warehouseData.current = warehouseList;

    // 提取所有唯一的国家代码
    const uniqueCountries = [
      ...new Set(warehouseList.map((item: any) => item.countryCode)),
    ];

    // 创建国家代码到国家名称的映射
    const countryCodeToName: { [key: string]: string } = {
      US: "United States",
      DE: "Germany",
      FR: "France",
      PL: "Poland",
      IT: "Italy",
      GB: "United Kingdom",
      CA: "Canada",
      AU: "Australia",
      JP: "Japan",
      MY: "Malaysia",
      AE: "United Arab Emirates",
      NG: "Nigeria",
      ES: "Spain",
      CZ: "Czech Republic",
      CN: "China",
    };

    return {
      backgroundColor: {
        image: img, // 支持为 HTMLImageElement, HTMLCanvasElement，不支持路径字符串
        repeat: "no-repeat", // 是否平铺，可以是 'repeat-x', 'repeat-y', 'no-repeat'
      },
      geo: {
        id: "customGeo",
        map: "customMap", // 此处需与注册地图命名保持一致
        type: "map",
        zoom: 1.2,
        top: 130,
        label: {
          normal: {
            show: false,
            textStyle: {
              color: "#FFFFFF",
            },
          },
        },
        roam: false, //是否允许缩放
        itemStyle: {
          normal: {
            color: "#222A50", //地图背景色，用到组件配置的变量
            borderColor: "#6997b8 ", //省市边界线
            borderWidth: 1.5,
            textStyle: "#fff",
            shadowColor: "#18639D",
            shadowOffsetX: 0,
            shadowOffsetY: 5,
          },
        },
        // 省份被选中的样式
        emphasis: {
          color: "#d0be20",
        },
        // 添加 regions 配置来高亮有仓库的国家
        regions: uniqueCountries.map((countryCode) => ({
          name: countryCodeToName[countryCode] || countryCode,
          selected: true,
          select: {
            itemStyle: {
              areaColor: "#d0be20", // 高亮颜色
              borderColor: "#d0be20", // 边框颜色
              borderWidth: 2,
              shadowColor: "rgba(0, 249, 177, 0.3)",
              shadowBlur: 10,
            },
           label: {
            show: true,
            color: "#FFFFFF",
           }
          },
        })),
      },
      series: [
        {
          type: "scatter",
          coordinateSystem: "geo",
          data: warehouseList?.map((item: any) => ({
            name: item.warehouseName,
            value: [processLng(Number(item.longitude)), Number(item.latitude)],
            symbolSize: 26,
            itemStyle: {
              color: "#00F9B1",
            },
            symbol:
              "image://https://uat-base.oss-cn-hangzhou.aliyuncs.com/wIcon.png",
          })),
        },
        {
          type: "lines",
          coordinateSystem: "geo",
          polyline: true,
          lineStyle: {
            color: "#00F9B1",
            width: 2,
            type: "dashed",
            opacity: 1,
            join: "miter",
          },
          data:
            warehouseList
              ?.filter((i) => i?.coordinatesNodes.length > 0)
              ?.map((item: any) => ({
                coords:
                  item?.coordinatesNodes.map((j) => [
                    processLng(Number(j.longitude)),
                    Number(j.latitude),
                  ]) || [],
              })) || [],
        },
      ],
    };
  }, [data]);

  // 添加新的 useEffect 来处理状态更新
  useEffect(() => {
    const warehouseList = data.map((i) => ({
      ...i,
      coordinatesNodes: JSON.parse(i.coordinatesNodes || "[]"),
    }));

    if (warehouseList && warehouseList.length > 0) {
      const echartInstance = mapChartRef.current?.getEchartsInstance();
      const tempList = warehouseList
        ?.filter((item: any) => !!item.videoUrl)
        .map((item: any) => {
          return {
            ...item,
            name: item.warehouseName,
            value: item.warehouseUtilization,
            warehouseLevel: item.warehouseLevel,
            lang: Number(item.longitude),
            lat: Number(item.latitude),
            imageUrl: item.imageUrl,
            showImage: true,
            totalInventory: item.totalInventory
              ? formatData(item.totalInventory)
              : 0,
            outboundInventory: item.outboundInventory
              ? formatData(item.outboundInventory)
              : 0,
            storageArea: item.storageArea ? item.storageArea : 0,
            icon:
              item.warehouseLevel === 1
                ? jin
                : item.warehouseLevel === 2
                ? yin
                : item.warehouseLevel === 3
                ? tong
                : icon_arrow,
            location: echartInstance?.convertToPixel({ geoId: "customGeo" }, [
              processLng(Number(item.longitude)),
              Number(item.latitude),
            ]),
          };
        });
      

      highlightWarehouseList.current = tempList;
      setWearhouseList(tempList);
      // 从国内仓库开始
      inWearhouseIndex.current = tempList.findIndex(
        (item: any) => item.name === "义乌集拼仓"
      );
      setCurrentWarehouseIndex(inWearhouseIndex.current);
      setEffect(inWearhouseIndex.current, tempList);
    }
  }, [data, setEffect]);

  return (
    <div
      style={{
        width: "100%",
        height: "100%",
        position: "relative",
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
      }}
    >
      <div>
        <ReactEChartsCore
          echarts={echarts}
          // style={{ width: '100%', height: '100%' }}
          style={{
            position: "absolute",
            top: 0,
            left: -33,
            width: "105%",
            height: "100%",
          }}
          option={option}
          notMerge={true}
          lazyUpdate={true}
          ref={mapChartRef}
        />
      </div>

      {/* 仓库初始画面 */}
      <>
        {/* {wearhouseList.map((item, index) => (
          <div
            key={item.name}
            style={{
              width: 220,
              height: 160,
              position: 'absolute',
              top: item.location?.[1]
                ? item.location?.[1] -
                  180
                : 0,
              left: item.location?.[0] ? item.location?.[0] - 142 : 0,
            }}
          >
            <div
              style={{ zIndex: nextHighlightWearhouse === index ? 999 : 2 }}
              className={` ${styles.tipSwrap} ${
                highlightWearhouse === index
                  ? 'animate__animated animate__heartBeat'
                  : ''
              }`}
            >
              <div className={styles.flexB}>
                <div className={styles.label}>
                  <Image
                    width={19}
                    height={item.warehouseLevel ? 21 : 16}
                    alt="icon"
                    src={item.icon.src}
                    style={{ verticalAlign: 'middle', marginRight: 3 }}
                  />
                  {item.name}
                </div>
                <div className={styles.flexE}>
                  <span
                    className={styles.label}
                    style={{ fontWeight: 400, fontSize: 12 }}
                  >
                    使用率
                  </span>
                  <span className={styles.value}>
                    {parseInt(item.value as string) || 0}
                    <span style={{ fontSize: 10 }}>%</span>
                  </span>
                </div>
              </div>
              <Image
                style={{ marginTop: 6, borderRadius: 3 }}
                width={196}
                height={110}
                alt="pic"
                src={item.imageUrl}
              />
            </div>
            <i
              className={styles.tipLine}
              style={{
                bottom: -18,
              }}
            />
          </div>
        ))} */}
      </>
      {/* 高亮仓库 */}
      {wearhouseList.map((item, index) => (
        <div
          className={`${styles.heighLightSwrap} animate__animated animate__zoomIn`}
          key={item.name}
          style={{
            display:
              highlight && highlightWearhouse === index ? "block" : "none",
            transformOrigin: `${
              item.location?.[0] ? item.location?.[0] - 130 + "px" : 0
            } ${item.location?.[1] ? item.location?.[1] - 260 + "px" : 0}`,
          }}
        >
          <div className={styles.name}>
            <Image
              width={19}
              height={16}
              alt="icon"
              src={item.icon.src}
              style={{ verticalAlign: "middle", marginRight: 3 }}
            />
            {item.name}
          </div>
          <div className={styles.wearInfoBox}>
            <div className={styles.wearInfoBoxItem}>
              <div className={styles.top}>
                <div className={styles.title}>
                  <Image
                    src={wIcon.src}
                    width={20}
                    height={20}
                    alt="icon"
                    className={styles.wIcon}
                  />
                  仓库面积
                </div>
              </div>
              <div className={styles.bottom}>
                <div className={styles.value}>
                  {item.storageArea}
                  <span className={styles.unit}>㎡</span>
                </div>
              </div>
            </div>
            <div className={styles.wearInfoBoxItem}>
              <div className={styles.top}>
                <div className={styles.title}>
                  <Image
                    src={wIcon.src}
                    width={20}
                    height={20}
                    alt="icon"
                    className={styles.wIcon}
                  />
                  库存
                </div>
              </div>
              <div className={styles.bottom}>
                <div className={styles.value}>
                  {item.inventoryNums || "-"}
                  <span className={styles.unit}>pcs</span>
                </div>
              </div>
            </div>
            <div className={styles.wearInfoBoxItem}>
              <div className={styles.top}>
                <div className={styles.title}>
                  <Image
                    src={wIcon.src}
                    width={20}
                    height={20}
                    alt="icon"
                    className={styles.wIcon}
                  />
                  出库量
                </div>
              </div>
              <div className={styles.bottom}>
                <div className={styles.value}>
                  {item.shipmentNums || "-"}
                  <span className={styles.unit}>pcs</span>
                </div>
              </div>
            </div>
            <div className={styles.wearInfoBoxItem}>
              <div className={styles.top}>
                <div className={styles.title}>
                  <Image
                    src={wIcon.src}
                    width={20}
                    height={20}
                    alt="icon"
                    className={styles.wIcon}
                  />
                  仓库使用率
                </div>
              </div>
              <div className={styles.bottom}>
                <div className={styles.value}>
                {Math.round(Number(item.usagerate || 0))}
                  <span className={styles.unit}>%</span>
                </div>
              </div>
            </div>
          </div>
          {renderPlayer(item, index)}
        </div>
      ))}
    </div>
  );
}

export default MapChart;
